package com.yanx.system.base.domain.entity;

import com.yanx.codegen.annotation.CodeGenClass;
import com.yanx.codegen.annotation.CodeGenField;
import com.yanx.common.core.domain.entity.BaseTimeEntity;
import com.yanx.system.base.domain.entity.rel.SysUserPost;
import com.yanx.system.base.domain.entity.rel.SysUserRole;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户对象 sys_user
 *
 * @author gotanks
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "SYS_USER")
@CodeGenClass(value = "用户", author = "gotanks")
public class SysUser extends BaseTimeEntity {

    private static final long serialVersionUID = 1L;

    /**
     * 用户账号
     */
    @Column
    @CodeGenField("用户账号")
    private String userName;

    /**
     * 用户昵称
     */
    @Column
    @CodeGenField("用户昵称")
    private String nickName;

    /**
     * 用户类型
     */
    @Column
    @CodeGenField("用户类型")
    private String userType;

    /**
     * 密码
     */
    @Column
    @CodeGenField(value = "密码", vo = false)
    private String password;

    /**
     * 帐号状态（0正常 1停用 2锁定）
     */
    @Column
    @CodeGenField("帐号状态")
    private String status;

    /**
     * 用户邮箱
     */
    @Column
    @CodeGenField("用户邮箱")
    private String email;

    /**
     * 手机号码
     */
    @Column
    @CodeGenField("手机号码")
    private String phonenumber;

    /**
     * 用户头像
     */
    @Column
    @CodeGenField("用户头像")
    private String avatar;

    /**
     * 用户头像
     */
    @Column
    @CodeGenField("用户性别")
    private String sex;

    /**
     * 最后登录IP
     */
    @Column
    @CodeGenField("最后登录IP")
    private String loginIp;

    /**
     * 最后登录时间
     */
    @Column
    @CodeGenField("最后登录时间")
    private LocalDateTime loginDate;

    /**
     * 部门ID
     * 外键
     */
    @Column
    @CodeGenField("部门ID")
    private Long deptId;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "userId", updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private List<SysUserRole> userRoles = new ArrayList<>();

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "userId", updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private List<SysUserPost> userPosts = new ArrayList<>();

    public boolean isAdmin() {
        return isAdmin(this.getId());
    }

    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }

    public void addUserRole(Long userId, Long roleId) {
        if (userRoles.stream().noneMatch(s -> s.getUserId().equals(userId) && s.getRoleId().equals(roleId))) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            userRoles.add(sysUserRole);
        }
    }
}
